package difficult;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Solution_51 {

    public static void main(String[] args) {
        Solution_51 model = new Solution_51();
        System.out.println(model.solveNQueens(4));
    }

    private List<List<String>> list;
    public List<List<String>> solveNQueens(int n) {
        list = new ArrayList<>();
        dps(new ArrayList<>(), n, new HashSet<>());
        return list;
    }

    private void dps(List<Integer> temp, int n, Set<String> visited) {
        if (temp.size() == n) {
            List<String> rst = new ArrayList<>();
            for (Integer index : temp) {
                StringBuilder s = new StringBuilder();
                for (int i = 0; i < n; i++) {
                    if (index == i) {
                        s.append("Q");
                    } else {
                        s.append(".");
                    }
                }
                rst.add(s.toString());
            }
            list.add(rst);
            return;
        }
        int i = temp.size() - 1;
        for (int j = 0; j < n; j++) {
            if (!visited.contains("1,0," + j) && !visited.contains("1,1" + -1 * (i + j)) && !visited.contains("1,-1" + (j - i))) {
                visited.add("1,0," + j);
                visited.add("1,1" + -1 * (i + j));
                visited.add("1,-1" + (j - i));
                temp.add(j);
                dps(temp, n, visited);
                temp.remove(temp.size() - 1);
                visited.remove("1,0," + j);
                visited.remove("1,1" + -1 * (i + j));
                visited.remove("1,-1" + (j - i));
            }
        }
    }
}
